import router from '@/router'
import { usePermissionStoreHook } from "@/store/permission"
import { useDictionaryStoreHook } from "@/store/dictionary"
import { ElNotification } from 'element-plus'
import storage from '@/utils/storage'

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async (to, from) => {
  document.title = to.meta.title

  const permissionStore = usePermissionStoreHook()

  if (storage.get('accessToken')) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      return { path: '/' }
      //permissionStore.logout()
      //next()
    } else {
      try {
        
        if (permissionStore.roles.length == 0) {
          var a = await permissionStore.getInfo();


          const dictionaryStore = useDictionaryStoreHook()
          await dictionaryStore.initDict()

          // const permissionStore = usePermissionStoreHook()
          //if (permissionStore.routes.length == 0) {
          permissionStore.setRoutes()

          permissionStore.dynamicRoutes.forEach((route) => {
            router.addRoute(route)
          })

          return to.fullPath
          //debugger
          //await router.replace(router.currentRoute.value.fullPath)
        }

       return true
        
        //await router.replace()
        //next({ ...to, replace: true })
        // }
        // else {
        // next()
        //}
      }
      catch (error) {
        
        permissionStore.logout()
        console.log(error)
        // ElNotification({
        //   message: error || 'Has Error',
        //   type: 'error',
        // })


        return { path: '/login' }
      }


      // next({ ...to, replace: true })
    }
  }
  else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      return true
    }
    else {
      return { path: '/login' }
    }
  }
})

router.afterEach(() => {

})
